package com.fjnu.service.impl;

import com.fjnu.annotation.ExceptionGlobalCatch;
import com.fjnu.dao.TagDao;
import com.fjnu.domain.entity.Tag;
import com.fjnu.service.TagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@ExceptionGlobalCatch
public class TagServiceImpl implements TagService {

    @Autowired
    private TagDao tagDao;

    @Override
    public List<Tag> getAllTags() {
        List<Tag> tags = tagDao.selectAll();
        return tags != null ? tags : java.util.Collections.emptyList();
    }

    @Override
    public int addTag(Tag tag) {
        if (tag == null) {
            throw new IllegalArgumentException("标签信息不能为空");
        }

        if (tag.getName() == null || tag.getName().trim().isEmpty()) {
            throw new IllegalArgumentException("标签名称不能为空");
        }

        // 检查标签是否已存在
        Tag existingTag = tagDao.selectByName(tag.getName().trim());
        if (existingTag != null) {
            throw new RuntimeException("标签名称已存在");
        }

        int result = tagDao.insert(tag);
        if (result == 0) {
            throw new RuntimeException("添加标签失败");
        }
        return result;
    }

    @Override
    @Transactional
    public int deleteTag(Integer tagId) {
        if (tagId == null || tagId <= 0) {
            throw new IllegalArgumentException("标签ID不能为空和小于等于0");
        }

        // 检查标签是否存在
        Tag tag = tagDao.selectById(tagId);
        if (tag == null) {
            throw new RuntimeException("标签不存在");
        }

        // 先删除文章标签关联关系
        tagDao.deleteArticleTagByTagId(tagId);

        // 再删除标签
        int result = tagDao.delete(tagId);
        if (result == 0) {
            throw new RuntimeException("删除标签失败");
        }
        return result;
    }
}